import type { DataNode } from 'rc-tree/lib/interface';
import type { AdminGroupTree } from '@/services/system/admin';
import type { ShortcutJsonProps } from '@/layouts/nested/SubSider/utils';

/**
 * 将从数据库中得到的数据格式转换成tree选择框用的格式
 * @param array [(path,cname,children)]
 * @returns 转换成tree的格式，例如：[{key,title,disabled,children}]
 */
export const convertToTreeData = (array: AdminGroupTree[]) => {
  const ren: DataNode[] = [];
  for (let i = 0; i < array.length; i += 1) {
    const currentNode: DataNode = {
      key: array[i].path,
      title: array[i].cname,
      disabled: true,
    };
    // 因为只有两级，就没有做递归了，直接for循环下一级了
    if (array[i].children) {
      const children: DataNode[] = [];
      for (let j = 0; j < array[i].children.length; j += 1) {
        children.push({
          key: array[i].children[j].path,
          title: array[i].children[j].cname,
          disabled: array[i].children[j].path === '/welcome/home',
        });
      }
      currentNode.children = children;
    }
    ren.push(currentNode);
  }
  return ren;
};

/**
 * 循环得到中文的title，由于菜单时两级别的，所以这个就没有做递归
 * @param key
 * @param treeData
 * @returns
 */
const getTitle = (key: string, treeData: DataNode[]) => {
  for (let i = 0; i < treeData.length; i += 1) {
    const children: DataNode[] = treeData[i].children || [];
    for (let j = 0; j < children.length; j += 1) {
      if (children[j].key === key) {
        return children[j].title?.toString();
      }
    }
  }
  return '';
};

/**
 * 将从快捷菜单设置页面中传入的字符串，变成可以保存到本地缓存的数据格式
 * @param targetKeys 例如：'/goods/list,/goods/brand',这里没有添加前缀admin，如果要作为页面跳转的时候，要添加admin
 * @param treeData  自己可以选择的菜单，这个是为了得到中文显示的title
 * @returns
 */
export const getShortcutJson = (
  targetKeys: string[],
  treeData: DataNode[],
): ShortcutJsonProps[] => {
  const ren: ShortcutJsonProps[] = [];
  targetKeys.forEach((key) => {
    const title = getTitle(key, treeData) || '';
    ren.push({ href: `/admin${key}`, title });
  });
  return ren;
};
